<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\ConsumeLog;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Utils\WxTemplate;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade;

/**
 * Class PayNoticeController
 * @package App\Http\Controllers\Mp
 * @author zjw
 * 微信支付通知
 */
class PayNoticeController extends Controller
{
    /**
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function index()
    {
        $app = Facade::payment();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            if ($message['return_code'] === 'SUCCESS') {
                $orderNo = $message['out_trade_no'];
                $rechargeOrder = RechargeOrder::where('recharge_no', $orderNo)->first();
                if (!$rechargeOrder || $rechargeOrder->pay_at !== null) { // 如果订单不存在或者订单已支付
                    return true;
                }
                if (array_get($message, "result_code") === "SUCCESS") { // 支付成功
                    if (array_get($message, "total_fee") != $rechargeOrder->pay_price * 100) { // 验证金额
                        return true;
                    }
                    if (!$rechargeOrder->checkSign($message)) {   // 签名验证
                        return true;
                    }
                    if ($rechargeOrder->changeToPay()) {
                        WxTemplate::sendMpRecharge($rechargeOrder); // 发送模板消息
                        return true;
                    } else {
                        return $fail("处理失败");
                    }
                } else if (array_get($message, "result_code") === "FAIL") { // 支付失败
                    $rechargeOrder->status = RechargeOrder::STATUS_PAY_FAIL;
                    $rechargeOrder->save();
                    return true;
                }
            } else {
                return $fail('通信失败');
            }
        });
        return $response;
    }
}